package web.action;

import com.opensymphony.xwork2.ActionSupport;
import entity.Extract;
import entity.MyFile;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import service.ExtractService;
import service.FileService;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileDownLoadAction extends ActionSupport {

    private FileService fs;
    private ExtractService es;

    private String phoneNum;
    private String extractCode;

    public String getExtract() {

        DetachedCriteria dc = DetachedCriteria.forClass(Extract.class);
        Map<String, String> map = new HashMap<String, String>();
        map.put("phone_num", phoneNum);
        map.put("extract_code", extractCode);
        dc.add(Restrictions.allEq(map));
        Extract extract = null;

        try{
            extract = es.getExtractByCondition(dc);

        }catch (IndexOutOfBoundsException e){
//            System.out.println("aaaa");
        }
        if (extract == null) {
            ServletActionContext.getRequest().setAttribute("notExtract","提取信息不存在!");
            return ERROR;
        } else {
            return getFileList(extract);
        }

    }


    private String getFileList(Extract extract) {

        HttpServletRequest request = ServletActionContext.getRequest();

        DetachedCriteria dc = DetachedCriteria.forClass(MyFile.class);
        dc.add(Restrictions.eq("extract", extract));
        dc.addOrder(Order.asc("upload_date"));
        List<MyFile> myFileList = fs.getFileByCondition(dc);

        if (myFileList.isEmpty()) {
            return NONE;
        } else {
            request.getSession().setAttribute("page",0);
            request.getSession().setAttribute("myFileListShadow", myFileList);
            request.getSession().setAttribute("myFileList", myFileList);
            return SUCCESS;
        }
    }

    public String downLoad() throws IOException {
        //*******文件名称是中文的下载*******
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();

        Long fileId = Long.valueOf(request.getParameter("file_id"));
        //获得下载文件
        MyFile file = fs.getFileById(fileId);
        //获得要下载的文件的名称
        String filename = file.getFilesFileName();//????.jpg
        //获得请求头中的User-Agent
        String agent = request.getHeader("User-Agent");
        //根据不同浏览器进行不同的编码
        String filenameEncoder = "";
        if (agent.contains("MSIE")) {
            // IE浏览器
            filenameEncoder = URLEncoder.encode(filename, "utf-8");
            filenameEncoder = filenameEncoder.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filenameEncoder = "=?utf-8?B?"
                    + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else {
            // 其它浏览器
            filenameEncoder = URLEncoder.encode(filename, "utf-8");
        }


        //要下载的这个文件的类型-----客户端通过文件的MIME类型去区分类型
        response.setContentType(request.getServletContext().getMimeType(filename));
        //告诉客户端该文件不是直接解析 而是以附件形式打开(下载)----filename="+filename 客户端默认对名字进行解码
        response.setHeader("Content-Disposition", "attachment;filename=" + filenameEncoder);
//        System.out.println(filenameEncoder);

        //获取文件的绝对路径
        String path = file.getFile_path() + "\\" + filename;
        //获得该文件的输入流
        InputStream in = new FileInputStream(path);
        //获得输出流---通过response获得的输出流 用于向客户端写内容
        ServletOutputStream out = response.getOutputStream();
        //文件拷贝的模板代码
        IOUtils.copy(in, out);
        file.setDownload_count(file.getDownload_count() + 1);
        out.close();
        in.close();
        return NONE;
    }

    public void setEs(ExtractService es) {
        this.es = es;
    }

    public void setFs(FileService fs) {
        this.fs = fs;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }

    public String getExtractCode() {
        return extractCode;
    }

    public void setExtractCode(String extractCode) {
        this.extractCode = extractCode;
    }

}
